<?php

namespace app\system\model;

use think\Model;
use think\model\concern\SoftDelete;
use app\admin\model\Admin;

/**
 * 部门模型
 */
class Dept extends Model
{
    /**
     * 软删除
     */
    use SoftDelete;
    protected $deleteTime = 'delete_time';
    protected $defaultSoftDelete = 0;

    /**
     * 数据表名称
     * @var string
     */
    protected $name = 'system_dept';

    /**
     * 自动写入时间戳
     * @var bool
     */
    protected $autoWriteTimestamp = true;

    /**
     * 关联成员 (部门负责人)
     */
    public function user()
    {
        return $this->belongsTo(Admin::class, 'admin_id');
    }

    /**
     * 生成 options
     */
    public static function getOptions()
    {
        $tree = self::where('status', 0)->order(['sort' => 'asc', 'id' => 'desc'])->select();
        return generateOptions($tree);
    }

    /**
     * 生成 tree
     */
    public static function getTrees($selected = [])
    {
        $tree = self::where('status', 0)->order(['sort' => 'asc', 'id' => 'desc'])->select();
        return generateTree($tree, 0, $selected);
    }

    /**
     * 读取某个部门下的所有子部门 - 包含自己
     * @param $id 部门id
     */
    public static function getDeptId($id)
    {
        return array_merge([$id], self::getDept($id));
    }

    /**
     * 读取某个部门下的所有子部门 - 不包含自己
     * @param $id 部门id
     */
    public static function getDept($id)
    {
        $arr = [];
        $data = self::where('status', 0)->where('pid', $id)->select();
        foreach ($data as $value) {
            $arr[] = $value['id'];
            $arr = array_merge($arr, self::getDept($value['id']));
        }
        return $arr;
    }
}
